#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <arpa/inet.h>
#include <strings.h>
namespace Client
{
    using namespace std;
    class udpClient
    {
    public:
        udpClient(const string& serverIp,const uint16_t& serverPort)
        :_sockfd(-1)
        ,_serverPort(serverPort)
        ,_serverIp(serverIp)
        {}
        void initClient()
        {
            //创建socket
            _sockfd=socket(AF_INET,SOCK_DGRAM,0);
            if(-1==_sockfd)
            {
                cout<<"socket error"<<errno<<":"<<strerror(errno)<<endl;
                exit(2);
            }
            cout<<"socket syuccess"<<":"<<_sockfd<<endl;
        }
        static void* readMessage(void* args)//类内创建线程,有个this指针干扰
        {
            int sockfd=*static_cast<int*>(args);
            pthread_detach(pthread_self());
            while(1)
            {
                //接收服务端发送的数据
                char buffer[1024];
                struct sockaddr_in temp;
                socklen_t len=sizeof(temp);
                size_t s=recvfrom(sockfd,buffer,sizeof(buffer),0,(struct sockaddr*)&temp,&len);
                if(s>0)
                {
                    buffer[s]=0;//字符串以'\0'结尾
                }
                cout<<buffer<<endl;
            }
            return nullptr;
        }
        void run()
        {
            pthread_create(&_reader,nullptr,readMessage,(void*)&_sockfd);
            struct sockaddr_in server;
            memset(&server,sizeof(server),0);//初始化为全0
            server.sin_family=AF_INET;
            server.sin_addr.s_addr=inet_addr(_serverIp.c_str());
            server.sin_port=htons(_serverPort);//主机转网络
            string message;
            char cmdline[1024];
            while(1)
            {
                //cerr<<"Please Enter#";
                // cin>>message;
                fprintf(stderr,"Enter#");
                fflush(stderr);
                fgets(cmdline,sizeof(cmdline),stdin);
                cmdline[strlen(cmdline)-1]=0;
                message=cmdline;
                //发送数据,sendto的时候，操作系统会帮我们自动绑定客户端端口+IP地址
                sendto(_sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&server,sizeof(server));
                
            }
        }
        ~udpClient()
        {}
    private:
        int _sockfd;
        uint16_t _serverPort;
        string _serverIp;
        pthread_t _reader;//读线程
    };
}
